package com.ciei.dpagm.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ciei.dpagm.common.enums.ErrorCodeEnum;
import com.ciei.dpagm.common.service.BaseService;
import com.ciei.dpagm.entity.Files;
import com.ciei.dpagm.mapper.FilesMapper;
import com.ciei.dpagm.util.*;
import com.ciei.dpagm.util.APP;
import com.ciei.dpagm.util.CompressUtils;
import com.ciei.dpagm.util.FileUtil;
import com.ciei.dpagm.util.JsonUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class FilesService extends BaseService<FilesMapper, Files> {

    @Value("${baseFilePath}")
    private String baseFilePath;

    private String filePath = "files/";

    public JSONObject uploadFileVue(HttpServletRequest request,String id,String typeId) {
        JSONObject jsonObject = new JSONObject();
        if(id!=null){
            jsonObject.put("relationId",id);
        }
        if(typeId!=null){
            jsonObject.put("relationTypeId",typeId);
        }
        String uploadPath = baseFilePath + this.filePath;
        // 检查文件目录是否存在并且创建
        checkDirs(uploadPath);
        String contentType = request.getContentType();
        if(StringUtils.isNotBlank(contentType) && contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)){
            JSONObject requestJsonObject = WebUtils.getRequestJsonObject(request);
            //获取fileName
            String fileName = requestJsonObject.getString("fileName");
            // 获取 fileContent 参数值
            String fileContent = requestJsonObject.getString("fileContent");
            if (StringUtils.isNotBlank(fileName)) {
                String randomFileName = FileUtils.getRandomFileName(fileName);
                File uploadedFile = new File(uploadPath, randomFileName);
                FileUtils.base64ToFile(fileContent,uploadedFile);
                fillFileJsonResult(jsonObject,fileName,randomFileName,uploadPath,true);
            }
        }else {
            // 创建一个通用的多部分解析器
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession()
                    .getServletContext());
            // 判断 request 是否有文件上传,即多部分请求
            if (multipartResolver.isMultipart(request)) {
                // 转换成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                // 取得request中的所有文件名
                Iterator<String> iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    // 取得上传文件
                    MultipartFile multipartFile = multiRequest.getFile(iter.next());
                    if (multipartFile != null) {
                        // 取得当前上传文件的文件名称
                        String fileName = multipartFile.getOriginalFilename();
                        if (StringUtils.isNotBlank(fileName)) {
                            try {
                                String randomFileName = FileUtils.getRandomFileName(fileName);
                                File uploadedFile = new File(uploadPath, randomFileName);
                                multipartFile.transferTo(uploadedFile);
                                fillFileJsonResult(jsonObject,fileName,randomFileName,uploadPath,true);
                            } catch (Exception e) {
                                return JsonUtil.getFail("上传文件失败");
                            }
                        }
                    }
                }
            }
        }
        return jsonObject;
    }

    public JSONArray uploadFolderVue(HttpServletRequest request) {
        JSONArray jsonArray = new JSONArray();
        String uploadPath = baseFilePath + this.filePath;
        // 检查文件目录是否存在并且创建
        checkDirs(uploadPath);
        String contentType = request.getContentType();
        if(StringUtils.isNotBlank(contentType) && contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)){
            JSONObject requestJsonObject = WebUtils.getRequestJsonObject(request);
            JSONArray fileArray = requestJsonObject.getJSONArray("fileList");
            if (fileArray != null && !fileArray.isEmpty()){
                for (int i = 0; i < fileArray.size(); i++) {
                    JSONObject fileJsonObject = fileArray.getJSONObject(i);
                    //获取fileName
                    String fileName = fileJsonObject.getString("fileName");
                    // 获取 fileContent 参数值
                    String fileContent = fileJsonObject.getString("fileContent");
                    if (StringUtils.isNotBlank(fileName)) {
                        String randomFileName = FileUtils.getRandomFileName(fileName);
                        File uploadedFile = new File(uploadPath, randomFileName);
                        FileUtils.base64ToFile(fileContent,uploadedFile);
                        JSONObject jsonObject = new JSONObject();
                        fillFileJsonResult(jsonObject,fileName,randomFileName,uploadPath,false);
                        jsonArray.add(jsonObject);
                    }
                }
            }
        }else {
            // 创建一个通用的多部分解析器
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession()
                    .getServletContext());
            // 判断 request 是否有文件上传,即多部分请求
            if (multipartResolver.isMultipart(request)) {
                // 转换成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                // 取得request中的所有文件名
                Iterator<String> iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    // 取得上传文件
                    List<MultipartFile> multipartFiles = multiRequest.getFiles(iter.next());
                    if (multipartFiles != null && !multipartFiles.isEmpty()) {
                        for (MultipartFile multipartFile : multipartFiles){
                            // 取得当前上传文件的文件名称
                            String fileName = multipartFile.getOriginalFilename();
                            if (StringUtils.isNotBlank(fileName)) {
                                try {
                                    String randomFileName = FileUtils.getRandomFileName(fileName);
                                    File uploadedFile = new File(uploadPath, randomFileName);
                                    multipartFile.transferTo(uploadedFile);
                                    JSONObject jsonObject = new JSONObject();
                                    fillFileJsonResult(jsonObject,fileName,randomFileName,uploadPath,false);
                                    jsonArray.add(jsonObject);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
        }
        return jsonArray;
    }


    /**
     * 填充文件json返回结果信息
     * @param jsonObject
     * @param fileName
     * @param randomFileName
     * @param uploadPath
     * @param convertToBase64
     */
    public void fillFileJsonResult(JSONObject jsonObject,String fileName,String randomFileName,String uploadPath,Boolean convertToBase64){
        jsonObject.put("name",fileName);
        jsonObject.put("url","uploads/" + this.filePath + randomFileName);
        int lastIndexOf = fileName.lastIndexOf(".");
        jsonObject.put("fileType",lastIndexOf == -1 ? "" : fileName.substring(lastIndexOf));
        if (convertToBase64){
            jsonObject.put("base64",FileUtils.fileToBase64(uploadPath + randomFileName));
        }
    }

    /**
     * 上传
     * 注:此格式处理前端拦截问题，同名文件覆盖上传需获取数据处理，uploadFile方法格式会被前端拦截掉.
     * @param request
     * @param id
     * @param typeId
     * @return
     */
    public JSONObject upload(HttpServletRequest request, String id, String typeId) {
        return JsonUtil.getSuccess("").fluentPut(APP.DATA,uploadFileVue(request, id, typeId));
    }

    /**
     * 上传文件夹
     * 注:此格式处理前端拦截问题，同名文件覆盖上传需获取数据处理，uploadFile方法格式会被前端拦截掉.
     * @param request
     * @return
     */
    public JSONObject uploadFolder(HttpServletRequest request) {
        return JsonUtil.getSuccess("").fluentPut(APP.DATA,uploadFolderVue(request));
    }

    /**下载文件(如果是多个文件，压缩成zip格式)
     * @param data
     * @param response
     * @return
     */
    public void download(JSONObject data, HttpServletResponse response){
        JSONArray filesArray = data.getJSONArray("files");
        if (filesArray == null || filesArray.isEmpty()){
            return;
        }
        List<Files> filesList = filesArray.toJavaList(Files.class);
        filesList.forEach(f-> f.setPath(baseFilePath + f.getPath().replaceFirst("uploads/" , "")));
        String filename;
        String filePath;
        File compressFile = null;
        //如果是一个文件
        if (filesList.size() == 1) {
            Files fileData = filesList.get(0);
            filename = fileData.getFileName();
            filePath = fileData.getPath();
        } else {
            filename = data.getString("downFileName") + ".zip";
            filePath = baseFilePath + UUID.randomUUID() + filename;
            Map<String,String> compressFileMap = new LinkedHashMap();
            String fname;
            int i = 0;
            for (Files files:filesList){
                fname = files.getFileName();
                if (compressFileMap.containsValue(fname)){
                    i+=1;
                    compressFileMap.put(files.getPath(),fname.substring(0,fname.lastIndexOf(".")) + "("+ i +")." + fname.substring(fname.lastIndexOf(".") + 1));
                }else {
                    compressFileMap.put(files.getPath(),fname);
                }
            }
            try {
                compressFile = CompressUtils.compressFile(compressFileMap, filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        File file = new File(filePath);
        response.setContentType("application/octet-stream");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("File-Md5", FileUtils.getFileMd5(filePath));
        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
        //删除临时文件
        if (compressFile != null && compressFile.exists()) {
            compressFile.delete();
        }
    }

    /**文件预览
     * @param data
     * @return
     */
    public JSONObject preview(JSONObject data){
        String filePath = data.getString("filePath");
        String fileBase64 = "";
        if (StringUtils.isNotBlank(filePath)){
            String path = baseFilePath + filePath.replaceFirst("uploads/", "");
            if (FileUtils.checkFileExistence(path)){
                fileBase64 = FileUtils.fileToBase64(path);
            }
        }
        return JsonUtil.getSuccess("").fluentPut(APP.DATA,fileBase64);
    }

    /**
     * 编辑文件名称
     * @param fileId
     * @param fileName
     * @return
     */
    public void editName(Integer fileId,String fileName){
        Files files = new Files();
        files.setFileId(fileId);
        files.setFileName(fileName);
        updateById(files);
    }

    /**
     * 编辑文件名称
     * @param data
     */
    public JSONObject editName(JSONObject data){
        Integer fileId = data.getInteger("fileId");
        String fileName = data.getString("fileName");
        if (fileId == null || StringUtils.isBlank(fileName)){
            return JsonUtil.getFail(ErrorCodeEnum.INVALID_PARAM,"缺少参数,请检查!");
        }
        Files files = findById(fileId);
        if (files == null){
            return JsonUtil.getFail(ErrorCodeEnum.DATA_NOT_FOUND,"找不到对应的文件数据!");
        }
        editName(fileId,fileName);
        return JsonUtil.getSuccess("");
    }

    /**
     * 删除文件
     * @param data
     */
    public JSONObject deleteFile(JSONObject data){
        Integer fileId = data.getInteger("fileId");
        if (fileId != null){
            Files files = findById(fileId);
            if (files != null){
                deleteFileData(Arrays.asList(files));
            }
        }
        String filePath = data.getString("filePath");
        if(StringUtils.isNotBlank(filePath)){
            String uploadPath = baseFilePath + this.filePath;
            // 检查文件目录是否存在并且创建
            checkDirs(uploadPath);
            int lastIndexOf = filePath.lastIndexOf("/");
            if(lastIndexOf != -1){
                String fileName = filePath.substring(lastIndexOf + 1);
                removeFile(uploadPath + fileName);
            }
        }
        return JsonUtil.getSuccess("");
    }


    private void checkDirs(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
    }
    private void checkFile(String path){
        File file = new File(path);
        if(file.exists()){
            file.delete();
        }
    }
    public void removeFile(Integer relationTypeId,Integer relationId){
        QueryWrapper<Files> wrapper = new QueryWrapper<>();
        wrapper.eq("relation_type_id",relationTypeId);
        wrapper.eq("relation_id",relationId);
        remove(wrapper);
    }

    /**
     * 附件JSON数据转实体
     * @param data          附件JSON数据
     * @param fileId    附件关联ID
     * @return
     */
    public Files json2Files(JSONObject data,Integer fileId) {
        Files files = new Files();

        if (fileId!=null){
            files.setFileId(fileId);
        }
        files.setFileName(data.getString("name"));
        files.setFileType(data.getString("fileType"));
        files.setPath(data.getString("url"));
        return files;
    }

    /**
     * 获取文件列表
     * @param relationTypeId
     * @param relationId
     * @return
     */
    public List<Files> getFileList(@NotNull Integer relationTypeId, @NotNull Integer relationId){
        LambdaQueryWrapper<Files> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Files::getRelationTypeId,relationTypeId)
                .eq(Files::getRelationId,relationId);
        return list(lambdaQueryWrapper);
    }

    /**
     * 获取文件列表
     * @param relationTypeId
     * @param relationIdList
     * @return
     */
    public List<Files> getFileList(@NotNull Integer relationTypeId, @NotNull List<Integer> relationIdList){
        if(relationIdList.isEmpty()){
            return new ArrayList<>();
        }
        LambdaQueryWrapper<Files> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Files::getRelationTypeId,relationTypeId)
                .in(Files::getRelationId,relationIdList);
        return list(lambdaQueryWrapper);
    }

    /**
     * 获取文件列表
     * @param relationTypeIdList
     * @param relationId
     * @return
     */
    public List<Files> getFileList(List<Integer> relationTypeIdList, @NotNull Integer relationId){
        if(relationTypeIdList.isEmpty()){
            return new ArrayList<>();
        }
        LambdaQueryWrapper<Files> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Files::getRelationTypeId,relationTypeIdList)
                .eq(Files::getRelationId,relationId);
        return list(lambdaQueryWrapper);
    }

    /**
     * 获取文件列表
     * @param relationTypeIdList
     * @param relationIdList
     * @return
     */
    public List<Files> getFileList(List<Integer> relationTypeIdList,List<Integer> relationIdList){
        if(relationIdList.isEmpty()){
            return new ArrayList<>();
        }
        if(relationTypeIdList.isEmpty()){
            return new ArrayList<>();
        }
        LambdaQueryWrapper<Files> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Files::getRelationTypeId,relationTypeIdList)
                .in(Files::getRelationId,relationIdList);
        return list(lambdaQueryWrapper);
    }

    /**
     * 删除文件数据
     * @param fileList
     */
    public void deleteFileData(List<Files> fileList){
        if(!fileList.isEmpty()){
            List<Integer> fileIdList = fileList.stream().map(Files::getFileId).collect(Collectors.toList());
            List<String> filePathList = fileList.stream().map(Files::getPath).collect(Collectors.toList());
            for(String filePath : filePathList){
                deleteFile(filePath);
            }
            removeByIds(fileIdList);
        }
    }

    /**
     * 删除文件
     * @param filePath
     */
    public void deleteFile(String filePath){
        if(StringUtils.isBlank(filePath)){
            return;
        }
        String uploadPath = baseFilePath + this.filePath;
        // 检查文件目录是否存在并且创建
        checkDirs(uploadPath);
        int lastIndexOf = filePath.lastIndexOf("/");
        if(lastIndexOf == -1){
            return;
        }
        String fileName = filePath.substring(lastIndexOf + 1);
        removeFile(uploadPath + fileName);
    }

    /**
     * 删除文件
     * 检查文件是否存在，存在则删除
     * @param path  文件路径
     */
    private void removeFile(String path){
        File file = new File(path);
        if(file.exists()){
            file.delete();
        }
    }

    /**
     * 添加文件属性
     * @param fileArray
     * @param userId  当前用户Id
     * @param filesList 符合条件的文件列表
     * @param relationTypeId 文件关联类型ID
     * @param relationId  关联ID
     * @return
     */
    public List<Files> addFileProperty(JSONArray fileArray, Integer userId, List<Files> filesList, Integer relationTypeId, Integer relationId){
        if(fileArray != null && !fileArray.isEmpty()){
            for(int i =0;i<fileArray.size();i++){
                JSONObject fileData = fileArray.getJSONObject(i);
                Integer fileId = fileData.getInteger("fileId");
                if (fileId == null){
                    Files files = new Files();
                    files.setRelationId(relationId);
                    files.setRelationTypeId(relationTypeId);
                    files.setFileType(fileData.getString("fileType"));
                    files.setUploadTime(new Timestamp(System.currentTimeMillis()));
                    files.setUploadUserId(userId);
                    files.setPath(fileData.getString("url"));
                    files.setFileName(fileData.getString("name"));
                    filesList.add(files);
                }
            }
        }
        return filesList;
    }

    /**
     * 保存多个文件
     * @param fileArray
     * @param userId
     * @param relationTypeId
     * @param relationId
     */
    public void saveFiles(JSONArray fileArray, Integer userId, Integer relationTypeId, Integer relationId){
        List<Files> filesList = new ArrayList<>();
        addFileProperty(fileArray, userId,filesList,relationTypeId,relationId);
        if (!filesList.isEmpty()){
            saveBatch(filesList);
        }
    }

    /**
     * 修改文件
     * @param fileArray
     * @param userId
     * @param relationTypeId
     * @param relationId
     */
    public void updateFiles(JSONArray fileArray, Integer userId, Integer relationTypeId, Integer relationId){
        List<Files> oldFileList = getFileList(relationTypeId,relationId);
        List<Files> newFileList = fileArray.toJavaList(Files.class);
        //需要删除的文件Id列表
        List<Files> deleteIdList;
        List<Files> insertFileList = new ArrayList<>();
        addFileProperty(fileArray,userId,insertFileList,relationTypeId,relationId);
        List<Integer> newFileIdList = newFileList.stream().map(Files::getFileId).collect(Collectors.toList());
        deleteIdList = oldFileList.stream().filter(e ->!newFileIdList.contains(e.getFileId())).collect(Collectors.toList());

        if (!deleteIdList.isEmpty()){
            deleteFileData(deleteIdList);
        }
        if (!insertFileList.isEmpty()){
            saveBatch(insertFileList);
        }
    }

    /**
     * 删除文件
     * @param relationTypeId
     * @param relationIds
     */
    public void deleteFiles(Integer relationTypeId, List<Integer> relationIds){
        List<Files> fileList = getFileList(relationTypeId,relationIds);
        deleteFileData(fileList);
    }

    /**
     * 删除文件
     * @param relationTypeIds
     * @param relationId
     */
    public void deleteFiles(List<Integer> relationTypeIds, Integer relationId){
        List<Files> fileList = getFileList(relationTypeIds,relationId);
        deleteFileData(fileList);
    }

    /**
     * 生成json格式文件
     * @param jsonObject
     * @return 文件路径
     */
    public String createJsonFile(JSONObject jsonObject) {
        //把数据转换成json字符串
        String jsonString = JSONObject.toJSONString(jsonObject,new FastJsonFilter(), SerializerFeature.WriteMapNullValue);
        String fileName = UUID.randomUUID().toString().replace("-", "") + ".json";
        String folderPath = baseFilePath + filePath;
        checkDirs(folderPath);
        String path = folderPath + fileName;
        try(FileWriter writer = new FileWriter(path)) {
            //格式化json字符串
            jsonString = JsonFormatTool.formatJson(jsonString);
            //将格式化后的字符串写入文件
            writer.write(jsonString);
            return path;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 生成json格式文件
     * @param data
     * @return 文件路径
     */
    public String createJsonFile(Map<String,Object> data) {
        //把数据转换成json字符串
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String jsonString = gson.toJson(data);
        String fileName = UUID.randomUUID().toString().replace("-", "") + ".json";
        String folderPath = baseFilePath + filePath;
        checkDirs(folderPath);
        String path = folderPath + fileName;
        try(FileWriter writer = new FileWriter(path)) {
            //将格式化后的字符串写入文件
            writer.write(jsonString);
            return path;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 复制文件
     * @param fileArray
     * @param userId
     * @param relationTypeId
     * @param relationId
     */
    public void copyFiles(JSONArray fileArray, Integer userId, Integer relationTypeId, Integer relationId){
        if (fileArray == null || fileArray.isEmpty()){
            return;
        }
        List<Files> oldFileList = fileArray.toJavaList(Files.class);
        //需要复制的文件Id列表
        List<Integer> copyIdList = oldFileList.stream().filter(e ->e.getFileId() != null).map(Files::getFileId).collect(Collectors.toList());
        if (!copyIdList.isEmpty()){
            List<Files> copyFileList = findListByIds(copyIdList);
            if (!copyFileList.isEmpty()){
                copyFileList.forEach(e ->{
                    String sourcePath = baseFilePath + e.getPath().replaceFirst("uploads/" , "");
                    String newFileName = UUID.randomUUID().toString().replace("-", "") + e.getFileType();
                    String newPath = baseFilePath + filePath + newFileName;
                    FileUtil.copyFile(sourcePath,newPath);

                    e.setFileId(null);
                    e.setPath("uploads/" + filePath + newFileName);
                    e.setUploadTime(new Timestamp(System.currentTimeMillis()));
                    e.setUploadUserId(userId);
                    e.setRelationId(relationId);
                    e.setRelationTypeId(relationTypeId);
                });
                if (!copyFileList.isEmpty()){
                    saveBatch(copyFileList);
                }
            }
        }

    }

    /**
     *  修改文件内容
     * @param filePath
     * @param charsetName
     * @param prefix
     * @param suffix
     * @param replacementMap
     */
    public void replaceFileContent(String filePath,String charsetName,String prefix,String suffix,Map<String,String> replacementMap){
        if (replacementMap.isEmpty()){
            return;
        }
        String targetContent;
        String replacementContent;
        List<String> fileContent = new ArrayList<>();
        try(FileInputStream fis = new FileInputStream(filePath);
            InputStreamReader isr = new InputStreamReader(fis, charsetName);
            BufferedReader reader = new BufferedReader(isr)) {
            // 读取文件内容
            fileContent = reader.lines().collect(Collectors.toList());
            // 遍历文件内容，查找要替换的内容
            for (int i = 0; i < fileContent.size(); i++) {
                for(Map.Entry<String, String> replacement : replacementMap.entrySet()){
                    targetContent = prefix + replacement.getKey() + suffix;
                    replacementContent = replacement.getValue();
                    if (replacementContent != null && fileContent.get(i).contains(targetContent)) {
                        // 替换为新内容
                        fileContent.set(i, fileContent.get(i).replace(targetContent, replacementContent));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try(FileOutputStream fos = new FileOutputStream(filePath);
            OutputStreamWriter osw = new OutputStreamWriter(fos, charsetName);
                BufferedWriter writer = new BufferedWriter(osw)) {
            for (String line : fileContent) {
                writer.write(line);
                writer.newLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  修改文件内容
     * @param filePath
     * @param charsetName
     * @param prefix
     * @param suffix
     * @param replacementMapList
     */
    public void replaceFileContent(String filePath,String charsetName,String loopPrefix,String prefix,String suffix,List<Map<String,String>> replacementMapList){
        if (replacementMapList.isEmpty()){
            return;
        }
        String lineContent;
        String targetContent;
        String replacementContent;
        List<String> fileContent = new ArrayList<>();
        try(FileInputStream fis = new FileInputStream(filePath);
            InputStreamReader isr = new InputStreamReader(fis, charsetName);
            BufferedReader reader = new BufferedReader(isr)) {
            // 读取文件内容
            fileContent = reader.lines().collect(Collectors.toList());
            // 遍历文件内容，查找要替换的内容
            for (int i = 0; i < fileContent.size(); i++) {
                lineContent = fileContent.get(i);
                if (lineContent.contains(loopPrefix)) {
                    lineContent = lineContent.replace(loopPrefix,"");
                    if (lineContent.endsWith(suffix)) {
                        lineContent = lineContent.substring(0,lineContent.length()-suffix.length());
                        StringBuilder newContent = new StringBuilder();
                        for (Map<String,String> replacementMap : replacementMapList){
                            String newLineContent = lineContent + "";
                            for(Map.Entry<String, String> replacement : replacementMap.entrySet()){
                                targetContent = prefix + replacement.getKey() + suffix;
                                replacementContent = replacement.getValue();
                                if (replacementContent != null && lineContent.contains(targetContent)) {
                                    newLineContent = newLineContent.replace(targetContent,replacementContent);
                                }
                            }
                            newContent.append(newLineContent + "\n");
                        }
                        fileContent.set(i, newContent.toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try(FileOutputStream fos = new FileOutputStream(filePath);
            OutputStreamWriter osw = new OutputStreamWriter(fos, charsetName);
            BufferedWriter writer = new BufferedWriter(osw)) {
            for (String line : fileContent) {
                writer.write(line);
                writer.newLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
